﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace SortGUI
{
    public class SelectSort : SortBase
    {
        public override void Sort(int[] array)
        {
            Initialize();
            SelectionSortAlgorithm(array);
            Complete();
        }

        private void SelectionSortAlgorithm(int[] array)
        {
            int n = array.Length;

            for (int i = 0; i < n - 1; i++)
            {
                int minIndex = i;

                for (int j = i + 1; j < n; j++)
                {
                    if (array[j] < array[minIndex])
                    {
                        minIndex = j;
                        lastSwappedIndices[0] = minIndex;
                        lastSwappedIndices[1] = i;
                        count++;
                        SortNextStep();
                    }
                }

                Swap(ref array[minIndex], ref array[i]);
                swapped = true;
            }
        }

        public override void Initialize()
        {
            count = 0;
            updataColor(isInitialize = false);
        }

        public override void SortNextStep()
        {
            updateUiCallback(count, lastSwappedIndices, lastSortedIndex = 10000, swapped); // 更新UI
        }

        public override void Complete()
        {
            updateUiCallback(count, lastSwappedIndices, lastSortedIndex - 10000, swapped);
        }
    }
}